package com.west.common.imageloader;

import android.content.Context;
import android.text.TextUtils;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.west.common.app.AppOperator;

/**
 * @author hanyulang
 * @date 2018/10/12
 */
public class GlideImageLoader implements IImageLoader<ImageConfigImpl> {

    private static GlideImageLoader mLoader;

    public static GlideImageLoader getImageLoader(){
        if(mLoader == null){
            synchronized (AppOperator.class){
                if(mLoader == null){
                    mLoader = new GlideImageLoader();
                }
            }
        }
        return mLoader;
    }

    private GlideImageLoader(){}

    @Override
    public void loadImage(Context context, ImageConfigImpl param) {

        if (param.getImageView() == null) {
            throw new IllegalArgumentException("ImageView can not be null");
        }

        if (param.isCenterCrop() && param.isCircile()) {
            throw new IllegalArgumentException("circle image can not be set centerCrop to be");
        }

        RequestBuilder<?> builder;
        RequestOptions options = RequestOptions.placeholderOf(param.getPlaceHolder())
                .error(param.getErrorHolder());

        if (param.isCenterCrop()) {
            options.centerCrop();
        }

        if (param.isCircile()) {
            options.optionalCircleCrop();
        }

        if (param.isDont()) {
            options.dontAnimate();
        }

        if (param.isCancelCache()) {
            options.diskCacheStrategy(DiskCacheStrategy.NONE);
            options.skipMemoryCache(true);
        }

        if(param.getImageRadius() > 0){
            RoundedCorners corners = new RoundedCorners(param.getImageRadius());
            options.transforms(new CenterCrop(), corners);
        }

        if(param.getW_h() != null && param.getW_h().length > 1){
            options.override(param.getW_h()[0], param.getW_h()[1]);
        }

        if (param.isGif()) {
            builder = Glide.with(context).asGif();
        } else {
            builder = Glide.with(context).asBitmap();
        }
        if (TextUtils.isEmpty(param.getUrl())) {
            builder.load(param.getUid());
        } else {
            builder.load(param.getUrl());
        }

        builder.apply(options).into(param.getImageView());

    }

}
